<template>
  <!-- <div id="data-view"> -->
  <YkiteFullScreenContainer>
    <div class="data-view">
      <img v-if="defaultConfig.detailBackground" :src="defaultConfig.detailBackground" class="image-background" alt="">
      <!--      行头部-->
      <div class="dView-head">
        <header-bi :title="pageInfo.pageName" :headerData="pageInfo.header" v-if="pageInfo.header"></header-bi>
      </div>
      <!-- 时间范围 -->
      <a-row class="data-view-search" align="center" style="width: 100%;">
        <a-col :span="12">
          <a-space>
            <a-typography-text style="color: #fff;font-size: 20px; font-weight: 500">时间范围：</a-typography-text>
            <component
                :is="timeOptions.timeUnit === 0 ?'a-date-picker' : timeOptions.timeUnit === 1 ? 'a-month-picker' : 'a-year-picker'"
                v-model="timeOptions.timer"
                :format="timeOptions.timeUnit === 0 ?'YYYY-MM-DD' : timeOptions.timeUnit === 1 ? 'YYYY-MM' : 'YYYY'"></component>
            <a-button type="primary" class="datav-two-button" :style="{marginLeft:'10px'}" @click="handleSearch">查询
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="12" style="text-align: right;">
          <a-space>
            <a-button type="primary" v-for="(item,index) in dateList" :key="index"
                      :class="['datav-two-button', index==dateCheckIndex?'datav-two-button-active':'']"
                      @click="handleTimeType(item.value)">{{ item.label }}
            </a-button>
            <a-button type="primary" class="datav-two-button" :style="{marginLeft:'10px'}" @click="back">返回</a-button>
          </a-space>
        </a-col>
      </a-row>
      <!-- 行中间部分 -->
      <div class="dView-content">
        <div class="dView-content-list">
          <chart-wrapper :title="dataInfo.cardName">
            <template v-slot:chart>
              <div class="chart-wrapper-content">
                <component :is="EnumChartType[chartParams.chartType]"
                           :ref="setChartRef"
                           :configType="0"
                           isDownload
                           :public="{cardKey: chartParams.cardKey,chartType: chartParams.chartType, dashboardConfigId: chartParams.dashboardConfigId,tablePre:2}"
                           :totalType="0"></component>
              </div>
            </template>
          </chart-wrapper>
        </div>
        <div class="dView-content-list dView-content-list-table"
             v-show="dataInfo.tableInfo?.tableData?.length>0 && chartParams.chartType!=16 &&chartParams.chartType!=15">
          <chart-wrapper :title="dataInfo.cardName">
            <template #chart>
              <table-list ref="tableRef" @result="handleResult"></table-list>
            </template>
          </chart-wrapper>
        </div>
      </div>
    </div>
  </YkiteFullScreenContainer>
  <!-- </div> -->
</template>

<script lang="ts" setup>
import {onBeforeUnmount, onMounted, onUnmounted, ref} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {handleDataVChartData} from "@/utils/charts";
import HeaderBi from "@/views/bi/components/headerBi.vue";
import ChartWrapper from "@/views/bi/template/default/components/chart-wrapper.vue";
import TableList from "@/views/bi/template/default/components/table-list-scroll.vue";
import useLoading from '@/hooks/loading';
import {getChartInfo} from '@/api/dashboard/api';
import dayjs from "dayjs";

const {loading, setLoading} = useLoading(false);
import {getTimeObject, handleConfigChart, handlePreConfigChart} from '@/utils/charts';
import {getBiInfo} from "@/api/manage/station";
import {notification} from "@/hooks/my-design";

const chartRef = ref<any>(null);
const tableRef = ref<any>(null);
const props = defineProps({
  // 0 为指定日期选择起 1 为范围选择器
  configType: {
    type: Number,
    default: 1,
  },
})
const route = useRoute()
const router = useRouter();
const backUrl: any = router.currentRoute.value.query.referer;
const buttonList = ref(['电量', '功率', '下载']);
const cardInfo = {
  title: "实时总发电量",
  type: 1,
  option: handleDataVChartData(),
  unit: 'kwh',
  expand: {
    type: 1,
    data: [{
      name: '光伏',
      value: 124,
      unit: 'kwh'
    }, {
      name: '风能',
      value: 34,
      unit: 'kwh'
    }, {
      name: '其他',
      value: 1,
      unit: 'kwh'
    }, {
      name: '合计',
      value: 158,
      unit: 'kwh'
    }]
  }
};
const chartInfo = ref<any>({
  cardName: '',
  echartsOption: {},
  singleInfo: null,
  singleRightList: [],
});
const EnumChartType: any = {
  1: 'large-combine',
  2: 'large-combine',
  3: 'large-combine',
  4: 'large-stack',
  5: 'large-combine',
  6: 'large-pie',
  7: 'large-k',
  8: 'large-water',
  9: 'large-gauge',
  10: 'large-sankey',
  11: 'large-section',
  12: 'large-ranking',
  13: 'large-screen-status',
  14: 'card-base',
  15: 'large-table',
  16: 'large-table',
  17: 'card-chart-pie-statistics',
  18: 'large-combine',
};
const data = [{
  value: 70,
  name: '光伏',
}, {
  value: 80,
  name: '风能',
}, {
  value: 90,
  name: '其他',
}];

const hasScrollbar = ref(false);
const chartParams = ref<any>({});
const dateList = ref<any>([{
  value: 0,
  label: '日'
}, {
  value: 1,
  label: '月'
}, {
  value: 2,
  label: '年'
}]);
const dateCheckIndex = ref<number>(0);
// table图表数据
const dataInfo = ref<any>({
  tableInfo: {
    tableData: []
  }
});
const pageInfo = ref<any>({
  pageName: '',
  pageTemplate: 0,
  background: {
    type: "image",
    url: ''
  },
  cardList: {
    bottomList: [],
    leftTop: [],
    rightTop: []
  }
});

// default 模板背景配置
const defaultConfig = JSON.parse(import.meta.env.VITE_Bi_DEFAULT_CONFIG);

const timeOptions = ref<any>({
  timer: dayjs().format("YYYY-MM-DD"),
  timeUnit: 0,
});

const checkScrollbar = () => {
  const body = document.body;
  const html = document.documentElement;
  const hasScroll = html.clientHeight < html.scrollHeight || body.clientHeight < body.scrollHeight;
  hasScrollbar.value = hasScroll;
};

const setChartRef = (ref: any) => {
  chartRef.value = ref;
}

// 返回
const back = () => {
  router.back();
};


// 时间搜索
const handleSearch = () => {
  chartRef.value.handleTime(timeOptions.value);
  tableRef?.value.handleTime(timeOptions.value);

};

// 年月日
const handleTimeType = async (unit: number) => {
  dateCheckIndex.value = unit;
  timeOptions.value.timeUnit = unit;
  const params = {
    timeUnit: timeOptions.value.timeUnit,
    timer: dayjs(timeOptions.value.timer).format(unit == 0 ? 'YYYY-MM-DD' : unit == 1 ? 'YYYY-MM' : "YYYY")
  };
  chartRef.value.handleTime(params);
  tableRef?.value.handleTime(params);
}

// 时间变化处理函数
const timeBarChange = async (timer: any) => {
  timeOptions.value = timer;
  await fetchData();
};

// 数据获取函数
const fetchData = async () => {
  try {
    setLoading(true);
    const params = {
      configId: chartParams.value.dashboardConfigId,
      cardKey: chartParams.value.cardKey,
      deviceSn: chartParams.value.deviceSn ? chartParams.value.deviceSn : undefined,
      ...getTimeObject(timeOptions.value),
    };

    const res = await getChartInfo(params);
    // console.log('首页fetch')
    if (res.code === 200 && res.data) {
      chartInfo.value = {
        ...res.data,
        echartsOption: handlePreConfigChart(res.data.echartsOption),
      };
    } else {
      chartInfo.value = {
        cardName: '',
        echartsOption: {},
        singleInfo: null,
      };
    }
  } catch (error) {
    console.error('获取图表数据时出错:', error);
  } finally {
    setLoading(false);
  }
};

const handleResult = (data: any) => {
  // console.log(data, 'data')
  dataInfo.value = data;
}

const getInfo = async () => {
  try {
    // console.log(route.query)
    const {stationId, isPre} = chartParams.value;
    const res: any = await getBiInfo({stationId, isPre});
    if (res.code === 200 && !res.data.code) {
      pageInfo.value = {
        ...res.data
      };
    } else {
      notification(res)
    }
  } catch (e) {
    console.log(e, '大屏模板报错')
  }
}

/*************************** 方法区域 end ***************************/


/**
 * 组件加载完成
 */
onMounted(async () => {
  checkScrollbar();
  chartParams.value = route.query;
  if (chartParams.value.chartType == 16 || chartParams.value.chartType == 15) {
    dateCheckIndex.value = 2;
    timeOptions.value.timer = dayjs().format("YYYY");
    timeOptions.value.timeUnit = 2;
  } else {
    dateCheckIndex.value = 0;
    timeOptions.value.timer = dayjs().format("YYYY-MM-DD");
    timeOptions.value.timeUnit = 0;
  }
  getInfo();
  window.addEventListener('resize', checkScrollbar);
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', checkScrollbar);
});

/**
 * 组件卸载
 */
onUnmounted(() => {
  // stopInterval()
})

</script>

<style lang="less" scoped>
@font-size: 16px;
@font-size-mini: 14px;
@font-size-medium: 18px;
@font-size-large: 24px;
@color-w: white;

.grid-title-num {
  color: #F3921D;
}

.data-view {
  width: 100vw;
  height: 100vh;
  color: @color-w;
  font-family: Source Han Sans;
  display: flex;
  flex-direction: column;

  .image-background {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
    object-fit: cover;
    min-height: 800px;
  }
}

.data-view-search {
  width: 100%;
  padding: 12px 32px;
  box-sizing: border-box;

  :deep(.datav-two-button) {
    padding: 0 10px;
    font-size: 20px;
    font-weight: 500;
    background-color: #003837;
    border: 1px solid #fff;
    border-radius: var(--border-radius-large);

    &:hover {
      background: #00DFDA;
    }
  }

  .datav-two-button-active {
    background: #00DFDA;
  }

  :deep(.headers-button) {
    height: 20px;
    font-size: 15px;
  }
}

.dView-head {
  height: 80px;
  background-image: url("@/assets/bi/default/navbar.png");
  background-repeat: no-repeat;
  background-position: bottom;
  font-size: 28px;
  padding: 0 32px;
}

.dView-content {
  flex: 1;
  scrollbar-width: none;
  -ms-overflow-style: none;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 0 32px;

  .dView-content-list {
    height: 407px;
    margin-bottom: 16px;

    .chart-wrapper-content {
      width: 100%;
      height: 100%;
    }
  }

  .dView-content-list-multi {
    height: auto;

    .multi-li {
      height: 180px;
    }
  }

  .dView-content-list-table {
    height: auto;
  }

  .chart-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;

    .chart {
      width: 72%;
      height: 100%;
    }

    .description {
      width: 28%;
      height: 100%;
      font-size: 16px;
    }
  }
}

.dView-content::-webkit-scrollbar {
  display: none;
}

.back-button {
  bottom: 100px;
  right: 80px;
}

:deep(.arco-back-top-btn) {
  background-color: #fff;
  color: #0000FF;
}

.dView-foot {
  height: 50px;
}

.button-active {
  margin-left: 50px;
}

:deep(.arco-spin-mask) {
  background: transparent;
}
</style>
